<?php

namespace App\Commons\Libs\Annotations;

use Doctrine\Common\Annotations\AnnotationReader;
use ReflectionMethod;
use Arr;
use Str;

/**
 * 用户日志注解
 *
 * @date    2020-06-30 10:33:33
 * @version $Id$
 * @Annotation
 * @Target({"METHOD"})
 */
final class UserLog
{
    public static $_variables = [];
    /**
    * @Required()
    * 1管理员，2投资者用户，3居间商，4系统生成
    * @var int
    */
    public int $type;
    /**
    * @Required()
    *
    * @var string
    */
    public string $tpl;

    public function toArray()
    {
        $user = [];
        if (auth()->user()) {
            $user = auth()->user();
        }
        $variables = static::$_variables + $user;
        $note = Str::mustacheReplace($this->tpl, $variables);
        return [
            'type' => $this->type,
            'note' => $note
        ];
    }

    public static function tag($key, $value)
    {
        if (is_array($key)) {
            static::$_variables += $key;
        } else {
            static::$_variables[$key] = $value;
        }
    }

    public static function annotation(string $action)
    {
        [$ctrl, $method] = explode('@', $action);
        $rm = new ReflectionMethod($ctrl, $method);
        $reder = new AnnotationReader;

        $annotation = $reder->getMethodAnnotation($rm, self::class);

        if ($annotation) {
            return $annotation->toArray();
        }
    }
}
